<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="dataForm.categoryId" placeholder="分类" :rules="[{ required: true, message: '请选择分类', trigger: 'blur' }]">
              <el-option v-for="item in dict.categoryId" :key="item.code" :label="item.name" :value="parseInt(item.code)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="title">
            <el-input v-model="dataForm.title" placeholder="名称"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item prop="period" label="适用学段">
            <el-select v-model="dataForm.peroidCodeList" multiple placeholder="请选择适用学段">
              <el-option v-for="item in dict.period" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="scene" label="适用场景">
            <el-select v-model="dataForm.sceneCodeList" multiple placeholder="请选择适用场景">
              <el-option v-for="item in dict.scene" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="封面图" prop="pic">
            <el-upload class="avatar-uploader" :action="picUploadUrl" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="dataForm.pic" :src="dataForm.pic" class="avatar" />
              <el-icon v-else class="el-icon--upload" style="width: 200px"><upload-filled /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="scene" label="专题分类">
            <el-select v-model="dataForm.topicCodeList" multiple placeholder="请选择专题分类">
              <el-option v-for="item in dict.topic" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="活动" prop="activity">
            <el-input v-model="dataForm.activity" placeholder="请输入活动"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="主题" prop="theme">
            <el-input v-model="dataForm.theme" placeholder="请输入主题"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="课程类型" prop="type1">
            <el-select v-model="dataForm.type" placeholder="请选择类型">
              <el-option v-for="item in dict.type" :key="item.code" :label="item.name" :value="parseInt(item.code)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="配套教具" prop="tools">
            <el-input v-model="dataForm.tools" placeholder="请输入配套教具"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="价格" prop="price">
            <el-input-number v-model="dataForm.price" :precision="2" :step="0.1" placeholder="请输入价格" oninput="value=value.replace(/[^0-9.]/g,'')"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发布状态" prop="status">
            <el-select v-model="dataForm.status" placeholder="请选择状态">
              <el-option v-for="item in dict.status" :key="item.code" :label="item.name" :value="parseInt(item.code)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="排序" prop="orderNo">
            <el-input-number v-model="dataForm.orderNo" placeholder="请输入排序"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="简介" prop="introduction">
        <el-input type="textarea" v-model="dataForm.introduction" placeholder="请输入简介"></el-input>
      </el-form-item>
      <el-form-item label="推荐描述" prop="suggest">
        <editor v-model="dataForm.suggest" :init="{ height: 300 }"></editor>
      </el-form-item>

      <el-form-item label="详情" prop="details">
        <!-- 富文本编辑器, 容器 -->
        <editor v-model="dataForm.details" :init="{ height: 300 }"></editor>
        <!-- 自定义上传图片功能 (使用element upload组件) -->
        <el-upload :action="uploadUrl" :show-file-list="false" :before-upload="uploadBeforeUploadHandle" :on-success="uploadSuccessHandle" style="display: none">
          <el-button ref="uploadBtn" type="primary" size="small">{{ $t("upload.button") }}</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script lang="ts">
import { defineComponent, reactive } from "vue";
import baseService from "@/service/baseService";
import { useDebounce } from "@/utils/utils";
import "quill/dist/quill.snow.css";
import Quill from "quill";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import { IObject } from "@/types/interface";
import Tinymce from "@/components/tinymce";
export default defineComponent({
  components: { editor: Tinymce },
  setup() {
    return reactive({
      visible: false,
      imageUrl: "",
      uploadUrl: "",
      picUploadUrl: "",
      dict: {
        status: baseService.strDict("0:未发布,1:已发布"),
        type: baseService.strDict("1:平台课程,2:集团定制,3:自定义"),
        categoryId: [{ code: "", name: "" }],
        period: [
          { code: "学龄前", name: "学龄前" },
          { code: "小学低年级", name: "小学低年级" },
          { code: "小学高年级", name: "小学高年级" },
          { code: "初中", name: "初中" },
          { code: "高中", name: "高中" }
        ],
        scene: [
          { code: "公开课", name: "公开课" },
          { code: "校内课程", name: "校内课程" },
          { code: "校外课堂", name: "校外课堂" },
          { code: "课外活动", name: "课外活动" },
          { code: "研学活动", name: "研学活动" }
        ],
        topic: [
          { code: "航空科普", name: "航空科普" },
          { code: "飞行实操", name: "飞行实操" },
          { code: "图形化编程", name: "图形化编程" }
        ]
      },
      dataForm: {
        id: "",
        categoryId: "",
        title: "",
        pic: "",
        period: "",
        scene: "",
        activity: "",
        theme: "",
        tools: "",
        introduction: "",
        details: "",
        price: "",
        status: "",
        type: "",
        createAt: "",
        creator: "",
        updateAt: "",
        orderNo: "",
        updator: "",
        suggest: "",
        peroidCodeList: [] as IObject[],
        sceneCodeList: [] as IObject[],
        topicCodeList: [] as IObject[]
      },

      peroidCodeListDefault: [] as IObject[],
      sceneCodeListDefault: [] as IObject[],
      topicCodeListDefault: [] as IObject[],
      peroidList: [] as IObject[],
      sceneList: [] as IObject[],
      topicList: [] as IObject[],

      dataRule: {
        title: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        orderNo: [{ required: true, message: "请输入排序", trigger: "blur" }],
        pic: [{ required: true, message: "请上传封面图片", trigger: "blur" }],
        type: [{ required: true, message: "请选择课程类型", trigger: "blur" }],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
        introduction: [
          { required: true, message: "请输入简介", trigger: "blur" },
          { min: 2, max: 200, message: "长度在 2 到 200 个字符", trigger: "blur" }
        ]
      }
    });
  },
  computed: {
    dataRule() {
      return {};
    }
  },
  created() {
    this.dataFormSubmitHandle = useDebounce(this.dataFormSubmitHandle);

    this.picUploadUrl = `${app.api}/sys/oss/upload?token=${getToken()}`;
  },
  methods: {
    init: function () {
      this.visible = true;
      this.$nextTick(() => {
        baseService.urlDict("/fii/fiicoursecategory/dict/list?parentId=0").then((a) => {
          this.dict.categoryId = a;
        });
        this.peroidCodeListDefault = [];
        this.sceneCodeListDefault = [];
        this.topicCodeListDefault = [];

        this.$refs["dataFormRef"].resetFields();

        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      baseService.get("/fii/fiicourse/" + this.dataForm.id).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.dataForm = res.data;
      });
    },
    // 表单提交
    dataFormSubmitHandle() {
      this.$refs["dataFormRef"].validate((valid: boolean) => {
        if (!valid) {
          return false;
        }
        (!this.dataForm.id ? baseService.post : baseService.put)("/fii/fiicourse", {
          ...this.dataForm,
          peroidCodeList: [...this.dataForm.peroidCodeList, ...this.peroidCodeListDefault],
          sceneCodeList: [...this.dataForm.sceneCodeList, ...this.peroidCodeListDefault],
          topicCodeList: [...this.dataForm.topicCodeList, ...this.topicCodeListDefault]
        }).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.$message({
            message: this.$t("prompt.success"),
            type: "success",
            duration: 500,
            onClose: () => {
              this.visible = false;
              this.$emit("refreshDataList");
            }
          });
        });
      });
    },
    // 上传图片之前
    uploadBeforeUploadHandle(file: IObject) {
      if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
        this.$message.error(this.$t("upload.tip", { format: "jpg、png、gif" }));
        return false;
      }
    },
    // 上传图片成功
    uploadSuccessHandle(res: IObject) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
    },
    handleAvatarSuccess(res: IObject, file: IObject) {
      this.dataForm.pic = res.data.src;
    },
    beforeAvatarUpload(file: IObject) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 4;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 4MB!");
      }
      return isJPG && isLt2M;
    }
  }
});
</script>
